package com.flycent.hqhs.ui;


import cn.sharesdk.framework.ShareSDK;

import com.flycent.hqhs.App;
import com.flycent.hqhs.Constants;
import com.flycent.hqhs.ExitManager;
import com.flycent.hqhs.R;
import com.flycent.hqhs.ui.view.BadgeView;
import com.flycent.hqhs.util.FileUtil;
import com.flycent.hqhs.util.PreferenceUtil;

import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.Toast;

/**
 *  导航栏Activity
 * @author fbl
 */
@SuppressWarnings("deprecation")
public class MainTabActivity extends TabActivity implements android.widget.CompoundButton.OnCheckedChangeListener{
	RadioGroup tabs;
	private TabHost tabHost;

	public static final String TAB_TAG_MAIN = "tab_tag_main";         //首页
	public static final String TAB_TAG_CLASSIFY = "tab_tag_classify"; //分类
	public static final String TAB_TAG_EXPORT = "tab_tag_export";     //达人
	public static final String TAB_TAG_SHOPCAR= "tab_tag_shopcar";    //购物车
	public static final String TAB_TAG_MINE = "tab_tag_mine";         //我的
	
	public static final String MAIN_UNREAD_RECEIVER = "org.ocs.MainActivity";
	public static final String KEY_UNREAD_CATEGORY	= "org.ocs.cloudmessage.UNREAD_CATEGORY";
	public static final int VALUE_REFRESH_BADGEVIEW 	= 1;
	
	private static long exitTime = 0;
	RadioButton btn_message;
	public BadgeView badge;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.maintabs);
		
		ShareSDK.initSDK(this); //注册shareSDK 只需注册一次即可
		
		registerBoradcastReceiver();
		
		
		createSDCardDir();  // 在SD卡下创建文件夹
		
		tabs = (RadioGroup) this.findViewById(R.id.main_radio);
		btn_message = (RadioButton) tabs.findViewById(R.id.radio_button3);
		badge = new BadgeView(this, btn_message);
		badge.setBadgeBackgroundColor(getResources().getColor(R.color.holo_title));
		btn_message.setOnCheckedChangeListener(this);//消息界面需要多加一步，在checked的时候把消息界面先选中
		
		tabs.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.radio_button0:
					tabHost.setCurrentTabByTag(TAB_TAG_MAIN);
					break;
				case R.id.radio_button1:
					tabHost.setCurrentTabByTag(TAB_TAG_CLASSIFY);
					break;
				case R.id.radio_button2:
					tabHost.setCurrentTabByTag(TAB_TAG_EXPORT);
					break;
				case R.id.radio_button3:
					tabHost.setCurrentTabByTag(TAB_TAG_SHOPCAR);
					break;
					
				case R.id.radio_button4:
					tabHost.setCurrentTabByTag(TAB_TAG_MINE);
					break;

				default:
					break;
				}
			}
		});

		tabHost = getTabHost();
		App.getInstance().setTabHost(tabHost);
		
		tabHost.addTab(buildTabSpec(TAB_TAG_MAIN, R.string.main_home,
				R.drawable.tab_home_ico_one, new Intent(this, MainActivity.class))); //
		
		tabHost.addTab(buildTabSpec(TAB_TAG_CLASSIFY, R.string.main_classify,
				R.drawable.tab_home_ico_one,
		        new Intent(this, ClassifyActivity.class)));  //

		tabHost.addTab(buildTabSpec(TAB_TAG_EXPORT, R.string.main_expert,
		        R.drawable.tab_home_ico_one, new Intent(this, ExpertActivity.class))); //
		
		tabHost.addTab(buildTabSpec(TAB_TAG_SHOPCAR, R.string.main_shopcar,
		        R.drawable.tab_home_ico_one, new Intent(this, ShopCarActivity.class))); //
		
		tabHost.addTab(buildTabSpec(TAB_TAG_MINE, R.string.main_mine,
				R.drawable.tab_home_ico_one, new Intent(this,
		                MineActivity.class)));

		tabHost.setOnTabChangedListener(new OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {

				if (tabId.equals(TAB_TAG_MAIN)) {
					tabs.check(R.id.radio_button0);
				} else if (tabId.equals(TAB_TAG_CLASSIFY)) {
					tabs.check(R.id.radio_button1);
				} else if (tabId.equals(TAB_TAG_EXPORT)) {
					tabs.check(R.id.radio_button2);
				} else if (tabId.equals(TAB_TAG_SHOPCAR)) {
					tabs.check(R.id.radio_button3);
				} else if (tabId.equals(TAB_TAG_MINE)) {
					tabs.check(R.id.radio_button4);
				}
			}
		});

		ExitManager.getInstance().addActivity(this);
	}
		

	@Override
	protected void onStart() {
		super.onStart();
		updateBadge();
	}
	
	/** 更新购物车数目 */
	void updateBadge() {
		int num = PreferenceUtil.getInt(MainTabActivity.this, "mProductSize");
		
		if(num <= 0 ){
			if(badge.isShown()){
				badge.hide();
			}
		}else {
			badge.setText(num + "");
			if (!badge.isShown()) badge.show(true);
		}
		
	}

	
	
	private TabHost.TabSpec buildTabSpec(String tag, int labelId, int iconId,
			final Intent content) {
		return tabHost
				.newTabSpec(tag)
				.setIndicator(getString(labelId),
						this.getResources().getDrawable(iconId))
				.setContent(content);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int keyCode = event.getKeyCode();
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			exitApp();
			return true; //为了让代码不执行下去，如果不加的话会被执行2次
		}
		return super.dispatchKeyEvent(event);
	}

	/**
	 * 退出程序
	 */
	public void exitApp() {
		// 2次点击事件时间2秒以内
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			Toast.makeText(MainTabActivity.this, R.string.click_exit, Toast.LENGTH_SHORT)
					.show();
			exitTime = System.currentTimeMillis();
		} else {
			Constants.isFirstEntry = true;	
			Constants.isAppForground = false;	//退出
			this.finish();
		}
	}

	/**
	 * Exit the app
	 */
	public void exit() {
		Intent i = new Intent();
		i.setAction(Intent.ACTION_MAIN);
		i.addCategory(Intent.CATEGORY_HOME);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		this.startActivity(i);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			tabs.check(buttonView.getId());
		}
	}
	
	//在SD卡上创建一个文件夹
	public void createSDCardDir(){
		if(FileUtil.isSdcardReady() ){
			FileUtil.mkSdcardFileDirs(FileUtil.SDCARDPATH);
		}else {
			//没有找到存储卡
			return;
		}
	}
	
	
	private void registerBoradcastReceiver(){
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(Constants.ACTION_UPDATEBADGE);
		//注册广播      
		registerReceiver(updateBadgeBroadcastReceiver, myIntentFilter);
	}

	private BroadcastReceiver updateBadgeBroadcastReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(Constants.ACTION_UPDATEBADGE)){
				updateBadge();
			}
		}
	};
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		ShareSDK.stopSDK(this);
		if(updateBadgeBroadcastReceiver != null){
			unregisterReceiver(updateBadgeBroadcastReceiver);
		}
	}
}
